package com.hgy.fxui.controller;

import com.hgy.fxui.dao.UserDao;
import com.hgy.fxui.model.User;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

@Slf4j
@Controller
public class UserManagementController {
    @FXML
    private TextField searchField;

    @FXML
    private TableView<User> userTable;

    @FXML
    private TableColumn<User, String> idColumn;

    @FXML
    private TableColumn<User, String> usernameColumn;

    @FXML
    private TableColumn<User, String> realNameColumn;

    @FXML
    private TableColumn<User, String> roleColumn;

    @FXML
    private TableColumn<User, String> createTimeColumn;

    @FXML
    private TableColumn<User, Void> operationColumn;

    private UserDao userDao;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void fullInitialize() {
        initializeColumns();
        loadUsers();
    }

    private void initializeColumns() {
        // 设置单元格值工厂
        idColumn.setCellValueFactory(data -> new SimpleStringProperty(String.valueOf(data.getValue().getId())));
        usernameColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getUsername()));
        realNameColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getRealName()));
        roleColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getRole()));
        createTimeColumn.setCellValueFactory(data -> 
            new SimpleStringProperty(data.getValue().getCreateTime().format(DATE_FORMATTER)));

        // 设置操作列
        operationColumn.setCellFactory(col -> new TableCell<>() {
            private final Button editButton = new Button("编辑");
            private final Button deleteButton = new Button("删除");
            private final HBox box = new HBox(5, editButton, deleteButton);

            {
                editButton.getStyleClass().add("small-button");
                deleteButton.getStyleClass().add("small-button");
                deleteButton.getStyleClass().add("danger-button");

                editButton.setOnAction(e -> handleEdit(getCurrentUser()));
                deleteButton.setOnAction(e -> handleDelete(getCurrentUser()));
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty ? null : box);
            }

            private User getCurrentUser() {
                return getTableView().getItems().get(getIndex());
            }
        });
    }

    private void loadUsers() {
        try {
            List<User> users = userDao.findAll();
            userTable.setItems(FXCollections.observableArrayList(users));
        } catch (Exception e) {
            log.error("加载用户数据失败", e);
            showError("加载用户数据失败");
        }
    }

    @FXML
    private void handleSearch() {
        String searchText = searchField.getText();
        try {
            List<User> users;
            if (searchText == null || searchText.trim().isEmpty()) {
                users = userDao.findAll();
            } else {
                users = userDao.search(searchText);
            }
            userTable.setItems(FXCollections.observableArrayList(users));
        } catch (Exception e) {
            log.error("搜索用户失败", e);
            showError("搜索用户失败");
        }
    }

    @FXML
    private void handleReset() {
        searchField.clear();
        loadUsers();
    }

    @FXML
    private void handleAdd() {
        showUserDialog(null);
    }

    private void handleEdit(User user) {
        showUserDialog(user);
    }

    private void handleDelete(User user) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText(null);
        alert.setContentText("确定要删除用户 " + user.getUsername() + " 吗？");

        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            try {
                userDao.delete(user.getId());
                loadUsers();
            } catch (Exception e) {
                log.error("删除用户失败", e);
                showError("删除用户失败");
            }
        }
    }

    private void showUserDialog(User user) {
        Dialog<User> dialog = new Dialog<>();
        dialog.setTitle(user == null ? "添加用户" : "编辑用户");
        dialog.setHeaderText(null);

        // 设置对话框内容
        DialogPane dialogPane = dialog.getDialogPane();
        dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField username = new TextField();
        TextField password = new PasswordField();
        TextField realName = new TextField();
        ComboBox<String> role = new ComboBox<>(FXCollections.observableArrayList("ADMIN", "USER"));

        if (user != null) {
            username.setText(user.getUsername());
            realName.setText(user.getRealName());
            role.setValue(user.getRole());
            password.setPromptText("不修改请留空");
        }

        grid.add(new Label("用户名："), 0, 0);
        grid.add(username, 1, 0);
        grid.add(new Label("密码："), 0, 1);
        grid.add(password, 1, 1);
        grid.add(new Label("真实姓名："), 0, 2);
        grid.add(realName, 1, 2);
        grid.add(new Label("角色："), 0, 3);
        grid.add(role, 1, 3);

        dialogPane.setContent(grid);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == ButtonType.OK) {
                if (username.getText().trim().isEmpty()) {
                    showError("用户名不能为空");
                    return null;
                }
                if (user == null && password.getText().trim().isEmpty()) {
                    showError("密码不能为空");
                    return null;
                }
                if (realName.getText().trim().isEmpty()) {
                    showError("真实姓名不能为空");
                    return null;
                }
                if (role.getValue() == null) {
                    showError("请选择角色");
                    return null;
                }

                User result = user == null ? new User() : user;
                result.setUsername(username.getText());
                if (!password.getText().trim().isEmpty()) {
                    result.setPassword(password.getText());
                }
                result.setRealName(realName.getText());
                result.setRole(role.getValue());
                return result;
            }
            return null;
        });

        Optional<User> result = dialog.showAndWait();
        result.ifPresent(updatedUser -> {
            try {
                if (user == null) {
                    userDao.insert(updatedUser);
                } else {
                    userDao.update(updatedUser);
                }
                loadUsers();
            } catch (Exception e) {
                log.error("保存用户失败", e);
                showError("保存用户失败");
            }
        });
    }

    private void showError(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
